package com.ts.conch.auth.component;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.ts.conch.dao.ItsAdminRoleRelationDao;
import com.ts.conch.dao.ItsPermissionDao;
import com.ts.conch.dao.ItsRoleDao;
import com.ts.conch.entity.TsPermission;
import com.ts.conch.entity.TsRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SaAuthComponent
 * @Decription: 自定义权限验证接口扩展
 * @Author: IDai
 * @Date: 2021-09-15 10:58 星期三
 **/
@Component
public class SaAuthComponent implements StpInterface {
    @Autowired
    private ItsPermissionDao permissionDao;
    @Autowired
    private ItsRoleDao roleDao;
    @Autowired
    private ItsAdminRoleRelationDao adminRoleRelationDao;

    /** 日志打印工具 **/
    private static final Logger logger = LoggerFactory.getLogger(SaAuthComponent.class);

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        logger.info("[权限装配] - 程序[SaAuthComponent.getPermissionList] - 开始运行 - 获取用户权限码loginId:{}", loginId);
        List<String> permissionList = new ArrayList<>();
        if (loginId != null){
            List<TsPermission> permissions = permissionDao.queryAdminPermission(String.valueOf(loginId));
            if (CollectionUtil.isNotEmpty(permissions)){
                permissions.stream().forEach(permission -> permissionList.add(permission.getValue()));
                logger.info("[权限装配] - 程序[SaAuthComponent.getPermissionList] - 结束运行 - 用户权限码列表permissionList:{}", JSON.toJSON(permissionList));
                return permissionList;
            }
        }
        return null;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        logger.info("[角色装配] - 程序[SaAuthComponent.getRoleList] - 开始运行 - 获取用户角色名列表loginId:{}", loginId);
        List<String> roleList = new ArrayList<>();
        if (loginId != null){
            List<TsRole> roles = adminRoleRelationDao.getRoleList(String.valueOf(loginId));
            if (CollectionUtil.isNotEmpty(roles)){
                roles.stream().forEach(role -> roleList.add(role.getName()));
                logger.info("[权限装配] - 程序[SaAuthComponent.getRoleList] - 结束运行 - 获取用户角色名列表roleList:{}", JSON.toJSON(roleList));
                return roleList;
            }
        }
        return null;
    }
}
